-- accumulate_coin
-- Created by chengb Oct/20/2015
-- 成就：累积金币

-- 内部函数声明
local checkComplete;
local whenAttribBonus;
local whenPickGold;

-- 注册玩家获得属性的回调
EventMgr.register("google_achievement/accumulate_coin", event.DO_BONUS, function(bonus)
    whenAttribBonus(bonus);
end);

-- 关注拾取金币的事件
EventMgr.register("google_achievement/pick_workshop_money", event.PICK_UP_GOLD, function(args)
    whenPickGold(args);
end);

-- 检查成就完成
checkComplete = function()
    local curAmount = ME.user:queryAttrib("money");

    -- 遍历所有的子规则
    local ids = GoogleAchievementM.getIdsByRule("accumulate_coin");

    -- 判断是否是符合要求的成就
    local function isValidId(id)
        if true == GoogleAchievementM.isCompleted(id) then
            -- 已经完成了
            return false;
        end

        local config = GoogleAchievementM.query(id);
        local ruleArg = config["rule_arg"];
        if type(ruleArg) == 'table' then
            if type(ruleArg["require_amount"]) == 'number' and 
                curAmount < ruleArg["require_amount"] then
                -- 没有达到需求数量
                return false;
            end
        end

        return true;
    end

    for _, id in pairs(ids) do
        if isValidId(id) then
            -- 尝试完成成就
            GoogleAchievementM.tryComplete(id, 1);
        end
    end
end

-- 关注拾取金币的事件
whenPickGold = function(args)
    local amount = args.amount;
    if amount <= 0 then
        return;
    end
    
    checkComplete();
end

-- 注册玩家获得属性的回调
whenAttribBonus = function(bonus)
    -- 如果不是金币奖励，就不用管了
    if bonus[1] ~= 2 or bonus[2] ~= "money"  or bonus[3] <= 0 then
        return;
    end
        
    checkComplete();
end
